package edu.whu.assignment8.security;

import edu.whu.assignment8.dataobject.Role;
import edu.whu.assignment8.dataobject.User;
import edu.whu.assignment8.mapper.RoleMapper;
import edu.whu.assignment8.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DbUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);

        Role role = roleMapper.selectByName(user.getRole());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String auth: role.getAuthorityList()) {
            authorities.add(new SimpleGrantedAuthority(auth));
        }

        if(user == null) {
            throw new UsernameNotFoundException("User " + username + " is not found.");
        }

        return org.springframework.security.core.userdetails.User.builder()
                .username(username)
                //.password(new SecurityConfig().passwordEncoder().encode(user.getPassword()))
                .password(new BCryptPasswordEncoder().encode(user.getPassword()))
                .authorities(authorities.toArray(new GrantedAuthority[authorities.size()]))
                .build();
    }
}
